package com.atguigu.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/7/19 9:07
 */
public class Dwd_02_DwdTrafficUniqueVisitorDetail extends BaseAppV1 {
    public static void main(String[] args) {
        new Dwd_02_DwdTrafficUniqueVisitorDetail().init(
            3002,
            2,
            "Dwd_02_DwdTrafficUniqueVisitorDetail",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private ValueState<String> dateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState", String.class));
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    String date = dateState.value();
                    // 窗口的开始时间计算年月日
                    String today = AtguiguUtil.toDate(ctx.window().getStart());
                    
                    if (!today.equals(date)) {  // 跨天了, 或者第一次启动
                        // 第一个窗口
                        dateState.update(today);
                        
                        List<JSONObject> list = AtguiguUtil.<JSONObject>toList(elements);
                        //                        Collections.min(list, (o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));
                        JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                        out.collect(min);
                    }
                }
            })
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_UV_DETAIL));
    }
}
/*
1. 数据源:
    页面  启动 曝光 活动 错误
    
    启动日志:
        可以, 但是结果可能会偏小
        
        启动日志一般只有app才会有, 其他的访问方式不会有
     
     页面日志:
        不管什么访问方式, 总会有页面日志, 只需要把每个用户当天的第一条页面日志保留
    

2. 实现思路
    状态记录访问年月日
    
    如果今天和状态中不一样
        换天  , 这条数据保留, 更新状态
        
     如果今天和状态一样
        没有任何操作
        
    
    如果只要当天第一条, 而不是任何一条都可以, 这个还要考虑乱序
        水印+窗口
        
        找到当天的第一个窗口, 窗口内时间戳最小的就是当天一条
        
 

 */